package com.ubb.dbms.domain.queryResult;

import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

import com.ubb.dbms.domain.xml.Table;
import com.ubb.dbms.domain.xml.TableAttribute;

public abstract class RawDataConverter {
	
	public static final String FULL_PROJECTION = "*";
	public static final Map<String, String> FULL_PROJECTION_MAP = new HashMap<String, String>();
	
	static {
		FULL_PROJECTION_MAP.put(FULL_PROJECTION, FULL_PROJECTION);
	}
	
	public static Map<String, String> projectionArrayToMap(String[] projections) {
		if (projections == null) {
			return null;
		}
		
		Map<String, String> projectionsMap = new HashMap<String, String>();
		for (String projection : projections) {
			projectionsMap.put(projection, projection);
		}
		
		return projectionsMap;
	}
	
	/**
	 * 
	 * @param table
	 * @param row
	 * @param projection if is * then is SELECT *
	 * @return
	 */
	public static SelectedRow convertRawData(Table table, byte[] row, Map<String, String> projections) {
		if (row == null || projections == null || table == null) {
			return null;
		}
		
		SelectedRow selectedRow = new SelectedRow();
		
		int rowContor = 0;
		for (TableAttribute columnAttribute : table.getStructure().getAttributeList()) {
			String columnName = columnAttribute.getAttributeName();
			int columnLength = Integer.parseInt(columnAttribute.getLength());
			String columnType = columnAttribute.getType();
			if (projections.containsKey(FULL_PROJECTION) || projections.containsKey(columnName)) {
				if ("int".equalsIgnoreCase(columnType)) {								// int
					int intValue = ByteBuffer.wrap(row, rowContor, columnLength).getInt();
					selectedRow.addRowValue(columnName, intValue);
				} else {																// varchar
					String stringValue = new String(row, rowContor, columnLength).replaceAll("\u0000.*", "");
					selectedRow.addRowValue(columnName, stringValue);
				}
			}
			rowContor += columnLength;
		}
		
		return selectedRow;
	}
}
